package map;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * description: <a href="https://time.geekbang.org/column/article/8053">极客时间</a>
 *
 * @author <a href="zhaoyingling12@163.com">simon zhao</a>
 * @since 2023/3/25
 */
public class LinkedHashMapSample {
    public static void main(String[] args) {
        // 为 true 则表示 get操作也算作访问，不然只有put操作才算
        // 实现 removeEldestEntry 方法，即为自定义淘汰策略
        LinkedHashMap<String, String> accessOrderedMap = new LinkedHashMap<String, String>(16, 0.75F, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<String, String> eldest) { // 实现自定义删除策略，否则行为就和普遍Map没有区别
                return size() > 3;
            }
        };
        accessOrderedMap.put("Project1", "Valhalla");
        accessOrderedMap.put("Project2", "Panama");
        accessOrderedMap.put("Project3", "Loom");
        // 遍历结果
        // Project1:Valhalla
        // Project2:Panama
        // Project3:Loom
        accessOrderedMap.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });

        // 模拟访问
        accessOrderedMap.get("Project2");
        accessOrderedMap.get("Project2");
        accessOrderedMap.get("Project3");
        System.out.println("Iterate over should be not affected:");
        // 遍历结果(保持不变)
        // Project1:Valhalla
        // Project2:Panama
        // Project3:Loom
        accessOrderedMap.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });
        // 触发删除
        accessOrderedMap.put("Project4", "Mission Control");
        System.out.println("Oldest entry should be removed:");

        // 遍历结果(Project1被删除)
        // Project2:Panama
        // Project3:Loom
        // Project4:Mission Control
        accessOrderedMap.forEach((k, v) -> {// 遍历顺序不变
            System.out.println(k + ":" + v);
        });
    }
}

